package com.talent.core.protocol.mqtt.codec.encoder;

import com.talent.core.protocol.mqtt.enums.TlMqttQos;
import com.talent.core.protocol.mqtt.model.fix.TlMqttFixedHead;
import com.talent.core.protocol.mqtt.model.request.TlMqttPublishReq;
import com.talent.core.protocol.mqtt.model.variable.TlMqttPublishVariableHead;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName：TlConnackDecoder
 * @Author: hszhou
 * @Date: 2024/11/30 15:35
 * @Description: puback的编码
 */
@ChannelHandler.Sharable
public class TlMqttPublishEncoder extends MessageToByteEncoder<TlMqttPublishReq> {


    private static final  Logger logger = LoggerFactory.getLogger(TlMqttPublishEncoder.class);

    @Override
    protected void encode(ChannelHandlerContext ctx, TlMqttPublishReq req, ByteBuf out) throws Exception {
        logger.debug("进入【PUBLISH】的编码器编码消息");
        TlMqttFixedHead fixedHead = req.getFixedHead();
        int length = fixedHead.getLength();
        TlMqttPublishVariableHead variableHead = req.getVariableHead();


        int type =  getFixedHeaderByte(fixedHead);
        int qos = fixedHead.getQos();
        TlMqttQos mqttQos = TlMqttQos.valueOf(qos);

        //消息类型
        out.writeByte(type);
        //剩余长度
        out.writeByte(length);

        String topic = variableHead.getTopic();
        byte[] topicBytes = topic.getBytes();
        out.writeShort(topicBytes.length);
        out.writeBytes(topicBytes);
        Integer messageId = variableHead.getMessageId();
        if(mqttQos!=TlMqttQos.QOS0){
            out.writeShort(messageId);
        }
        Object content = req.getPayload().getContent();
        byte[] bytes =content.toString().getBytes();
        out.writeBytes(bytes);


    }



    private  int getFixedHeaderByte(TlMqttFixedHead header) {
        int ret = 0;
        ret |= header.getMessageType() << 4;
        if (header.getDup()!=0) {
            ret |= 0x08;
        }
        ret |= header.getQos() << 1;
        if (header.getRetain()!=0) {
            ret |= 0x01;
        }
        return ret;
    }

}
